package com.keyingbo.orm.framework.spring;

import com.keyingbo.orm.framework.impl.EntityStatment;
import com.keyingbo.orm.framework.util.ScanUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import javax.persistence.Table;
import java.util.List;

/**
 * DAO 受管Bean定义解析器。
 * @Auther: KEYB
 * @Date: 2019-4-28 11:29
 * @Description:
 */
public class DaoBeanDefinitionParser implements BeanDefinitionParser {
    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        Object source = parserContext.extractSource(element);
        RootBeanDefinition processor = new RootBeanDefinition(DaoAnnotationBeanPostProcessor.class);
        processor.setSource(source);
        processor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        parserContext.getReaderContext().registerWithGeneratedName(processor);
        BeanDefinitionRegistry registry = parserContext.getRegistry();
        List<Class<?>> clses = ScanUtils.scanEntityClasses(Table.class);
        for(Class<?> clz : clses){
            RootBeanDefinition def = new RootBeanDefinition(EntityStatment.class);
            def.setScope(BeanDefinition.SCOPE_SINGLETON);

            String strTemplateName ="dataSource";

            RuntimeBeanReference datasourceRef = new RuntimeBeanReference(strTemplateName);
            def.getPropertyValues().addPropertyValue("dataSource", datasourceRef);
            def.getPropertyValues().addPropertyValue("entityClass", clz);
            String beanName = clz.getSimpleName().toLowerCase()+"_dao";
            registry.registerBeanDefinition(beanName, def);
        }
        return null;
    }
}
